package com.qk.common.api;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qk.common.property.LogisticsProperties;
import com.qk.common.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:gzc
 * @Date: 2025/10/09 16:05
 * @Description:
 */
@Component
public class LogisticsApi {


    @Autowired
    private LogisticsProperties logisticsProperties;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public Map<String, Object> queryLogistics(Map<String, String> querys) throws Exception {
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + logisticsProperties.getAppcode());
        try {
            HttpResponse response = HttpUtils.doGet(logisticsProperties.getHost(), logisticsProperties.getPath(), logisticsProperties.getMethod(), headers, querys);
//            System.out.println(response.toString());
            //获取response的body
            String logisticsMessage = EntityUtils.toString(response.getEntity());
            // 解析完整响应
            JsonNode rootNode = objectMapper.readTree(logisticsMessage);
            // 检查API返回状态是否成功（code=0）
            if (rootNode.get("code").asInt() != 0) {
                throw new Exception("物流查询API调用失败：" + rootNode.get("desc").asText());
            }
            JsonNode data = rootNode.get("data");
            JsonNode list = data.get("list");
            //快递公司名称
            JsonNode name = data.get("name");
            //单号
            JsonNode number = data.get("number");
            Map<String, Object> map = new HashMap();
            map.put("list", list);
            map.put("name", name);
            map.put("number", number);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
